import MusicManager from "../../../MusicManager";
import DefensiveFacility from "../../facility/DefensiveFacility";
import HealthPoint from "../../funcObj/interface/HealthPoint";
import { FacilityType } from "../../info/GameEnum";
import { Global } from "../../info/Global";
import PlayerManager from "../../manager/PlayerManager";
import DefenseFlyer from "../DefenseFlyer";

const { ccclass, property } = cc._decorator;

/**
 * 近防炮子弹
 */
@ccclass
export default class Bullet extends DefenseFlyer {

    @property([cc.SpriteFrame])
    enemyFrames: cc.SpriteFrame[] = [];

    @property([cc.SpriteFrame])
    playerFrames: cc.SpriteFrame[] = [];

    @property(cc.Sprite)
    showBullte: cc.Sprite = null;

    init(base: DefensiveFacility, target?: HealthPoint) {
        super.init(base, target);

        if (this.player == PlayerManager.instance.controllerPlayer) {
            this.showBullte.spriteFrame = this.playerFrames[base.level == 8 ? 1 : 0];
        } else {
            this.showBullte.spriteFrame = this.enemyFrames[base.level == 8 ? 1 : 0];
        }

        let facilityInfo = Global.getFacilityInfo<{ 每等级攻击力: number[] }>(base.facilityType);
        this.atk = facilityInfo.每等级攻击力[base.level];
        let rate = 1 + Global.FacilityInfo[FacilityType.主基地].近防炮攻击.每等级加成[this.player.artilleryDamageBonusLevel] / 100
        this.atk = Math.ceil(this.atk * rate);
    }

    dispatch(target: HealthPoint) {
        super.dispatch(target);
        this.moveComp.setTarget(this.target.node.position, this.onArrive.bind(this));
        this.update(0);
        MusicManager.instance.play(MusicManager.instance.defenseCannonFire, this.node);
    }

    /**
     * 每帧对准目标
     * @param dt 
     */
    protected update(dt): void {
        // 对准怪物
        let targetPosition = this.target ? this.target.node.position : this.targetPosition;
        let thisPosition = this.node.position;
        let direction = cc.v2(targetPosition.x - thisPosition.x, targetPosition.y - thisPosition.y);
        let angle = cc.misc.radiansToDegrees(cc.Vec2.angle(direction, cc.v2(0, 1)));
        this.node.angle = direction.x > 0 ? 360 - angle : angle;
        this.moveComp.setTarget(targetPosition);
    }

    onArrive(): void {
        MusicManager.instance.play(MusicManager.instance.defenseCannonBomb, this.node);
        super.onArrive();
    }
}
